import pandas as pd
import json
import requests
import time

def exec_fine_tune(app) -> None :
    app.config['fine_tune_status'] = 'running'

    table = load_excel('data/Fine tune datas.xlsx')

    result = []

    start = time.time()

    for index, row in table.iterrows():
        print('exec: {}'.format(index))
        response = call_generativeaiservice(row=row)
        result.append({
            "Instruction": response['prompt'],
            "Answer": response['data']['gptReply']
        })
        time.sleep(1)
    
    with open("fine_tune_result.json", "w") as file:
        json.dump(result, file)

    end = time.time()

    execution_time = end - start

    print("fine tune done, execution time:", execution_time, "seconds")

    app.config['fine_tune_status'] = 'done'

def call_generativeaiservice(row):
    response = {
        'code': 0,
        'msg': 'success',
        'prompt': [''],
        'data': {
            'gptReply': ''
        }
    }
    try:
        siteId = 10008
        botId = '86A2EF45-7D46-EB11-8100-00155D081D0B'
        
        source = row['Source']
        if source == 'Comm100 KB':
            siteId = 10008
            botId = '86A2EF45-7D46-EB11-8100-00155D081D0B'
        elif source == 'UH':
            siteId = 10007
            botId = '76A2EF45-7D46-EB11-8100-00155D081D0B'
        elif source == 'Dropbot':
            siteId = 10009
            botId = '96A2EF45-7D46-EB11-8100-00155D081D0B'

        input = {
            "siteId": str(siteId),
            "botId": str(botId),
            "query" : row['Question'],
            "context" : {
                "subject": "",
                "history": []
            },
            "llm": "GPT4",
            "topArticles": 3
        }

        url = 'https://canvasapi.testing.comm100dev.io/generativeaiservice/gptbots/{}/query'.format(botId)

        headers = { 'content-type': 'application/json', 'X-Token': 'cc9dfc7473d3486dac06e1634d4ce38e' }
        res = requests.post(url=url, headers=headers, json=input)

        response = json.loads(res.text)
    except Exception as ex:
        print('exception', ex)
    
    return response

def load_excel(path):
    df = pd.read_excel(path, 'Training data')
    return df.loc[:,['Source', 'Question', 'History']]
